package com.hctforgreen.greenservice.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.format.Formatter;

public class FileCacheUtil {

	/**
	 * 遍历缓存目录，获取其内全部文件的总size
	 * 
	 * @param fileDirectoryPath
	 *            文件夹路径
	 * @param excludeFileList
	 *            要排除掉的文件、文件夹
	 * @return
	 */
	public String getFileDirectoryLength(Activity activity,
			String fileDirectoryPath, ArrayList<String> excludeFileList) {

		File fileDirectory = new File(fileDirectoryPath);
		long size = getFolderSize(fileDirectory, excludeFileList);
		return Formatter.formatFileSize(activity, size);

	}

	private long getFolderSize(File file, ArrayList<String> excludeFileList) {
		long size = 0;
		java.io.File[] fileList = file.listFiles();
		if (fileList == null) {
			return 0;
		}
		for (int i = 0; i < fileList.length; i++) {

			if (!excludeFileList.contains(fileList[i].getPath())) {

				continue;
			}

			if (fileList[i].isDirectory()) {
				size = size + getFolderSize(fileList[i], excludeFileList);
			} else {
				size = size + fileList[i].length();
			}
		}
		return size;
	}

	/**
	 * 
	 * @param fileDirectoryPath
	 *            SDCard缓存文件夹
	 * @param excludeFileList
	 *            要排除掉的文件、文件夹
	 */
	public void deleteFileDirectory(String fileDirectoryPath,
			ArrayList<String> excludeFileList) {

		File fileDirectory = new File(fileDirectoryPath);
		delete(fileDirectory, excludeFileList);

	}

	/**
	 * 
	 * @param fileDirectoryPath
	 *            SDCard缓存文件夹
	 */
	public void deleteFileDirectory(String fileDirectoryPath) {
		File fileDirectory = new File(fileDirectoryPath);
		delete(fileDirectory);

	}

	private void delete(File file) {

		if (file.isFile()) {
			file.delete();
			return;
		}

		if (file.isDirectory()) {
			File[] childFiles = file.listFiles();
			if (childFiles == null || childFiles.length == 0) {
				file.delete();
				return;
			}

			for (int i = 0; i < childFiles.length; i++) {
				delete(childFiles[i]);
			}
			file.delete();
		}

	}

	private void delete(File file, ArrayList<String> excludeFileList) {
		if (!excludeFileList.contains(file.getPath())) {
			return;
		}
		if (file.isFile()) {
			file.delete();
			return;
		}

		if (file.isDirectory()) {
			File[] childFiles = file.listFiles();
			if (childFiles == null || childFiles.length == 0) {
				file.delete();
				return;
			}

			for (int i = 0; i < childFiles.length; i++) {
				delete(childFiles[i], excludeFileList);
			}
			file.delete();
		}

	}

	/**
	 * 转换文件大小
	 * 
	 * @param fileS
	 * @return
	 */
	public static String FormetFileSize(long fileS) {
		DecimalFormat df = new DecimalFormat("#.00");
		String fileSizeString = "";
		if (fileS == 0) {
			fileSizeString = "0.00B";
		} else if (fileS < 1024) {
			fileSizeString = df.format((double) fileS) + "B";
		} else if (fileS < 1048576) {
			fileSizeString = df.format((double) fileS / 1024) + "K";
		} else if (fileS < 1073741824) {
			fileSizeString = df.format((double) fileS / 1048576) + "M";
		} else {
			fileSizeString = df.format((double) fileS / 1073741824) + "G";
		}
		return fileSizeString;
	}

	/**
	 * 复制文件（夹）到指定目标文件（夹）
	 * 
	 * @param resFile
	 *            源文件（夹）
	 * @param objFolderFile
	 *            目标文件（夹）
	 * @throws IOException
	 * 
	 */
	public static void copy(File resFile, File objFolderFile)
			throws IOException {
		if (!resFile.exists())
			return;
		if (!objFolderFile.exists())
			objFolderFile.mkdirs();
		if (resFile.isFile()) {
			File objFile = new File(objFolderFile.getPath() + File.separator
					+ resFile.getName());
			// 复制文件到目标地
			InputStream ins = new FileInputStream(resFile);
			FileOutputStream outs = new FileOutputStream(objFile);
			byte[] buffer = new byte[1024 * 512];
			int length;
			while ((length = ins.read(buffer)) != -1) {
				outs.write(buffer, 0, length);
			}
			ins.close();
			outs.flush();
			outs.close();
		} else {
			String objFolder = objFolderFile.getPath() + File.separator
					+ resFile.getName();
			File _objFolderFile = new File(objFolder);
			_objFolderFile.mkdirs();
			for (File sf : resFile.listFiles()) {
				copy(sf, new File(objFolder));
			}
		}
		deleteFile(resFile);
	}

	public static void deleteFile(File file) {
		if (file.exists()) {
			if (file.isFile()) {
				file.delete();
			} else if (file.isDirectory()) {
				File files[] = file.listFiles();
				if (files == null || files.length == 0) {
					file.delete();
					return;
				}
				for (int i = 0; i < files.length; i++) {
					deleteFile(files[i]);
				}
			}
			file.delete();
		} else {
			System.out.println("文件不存在！" + '\n');
		}
	}

	public static String getPath(Context context, Uri uri) {

		if ("content".equalsIgnoreCase(uri.getScheme())) {
			String[] projection = { "_data" };
			Cursor cursor = null;

			try {
				cursor = context.getContentResolver().query(uri, projection,
						null, null, null);
				int column_index = cursor.getColumnIndexOrThrow("_data");
				if (cursor.moveToFirst()) {
					return cursor.getString(column_index);
				}
			} catch (Exception e) {
				// Eat it
			}
		}

		else if ("file".equalsIgnoreCase(uri.getScheme())) {
			return uri.getPath();
		}

		return null;
	}
}
